package com.toplabs.unashu.aspect;

import com.toplabs.unashu.annotation.CurrentContent;
import com.toplabs.unashu.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * @author toplabs
 * @since 2022/11/21
 * <p>This java file was created by toplabs in 2022/11/21.
 * The following is the description information about this file:</p>
 * <p>description: 当前用户方法参数解析器</p>
 */
public class CurrentContentMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断是否支持使用@CurrentContent注解的参数; 如果该参数注解有@CurrentContent且参数类型是User
        return parameter.getParameterType().isAssignableFrom(User.class) && parameter.hasParameterAnnotation(CurrentContent.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        User loginUser = (User) webRequest.getAttribute("CurrentContent", RequestAttributes.SCOPE_REQUEST);
        if (loginUser != null) {
            return loginUser;
        }
        throw new MissingServletRequestPartException("CurrentContent");
    }
}
